#!/usr/bin/perl
#===========================================================
#
#   maidolist ( create a mailing list program )
#
#-----------------------------------------------------------
#
#   Copyright 2009 Takeshi SAKURAI (takeshi.sakurai@hde.co.jp)
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
#===========================================================
use strict;
use Fcntl;
use GDBM_File;

my $dbfile = "./maido.gdbm";
my $delim = "\t";

my $base = `pwd`;
chomp($base);

my $aliases = "/etc/aliases";
my $command = "|" . $base . "/maidodomo";

if ($#ARGV < 1) {
  print "usage: ./maidolist ml_name address...\n";
  exit 1;
}

my $ml = $ARGV[0];
my @addresses;
for (my $i=1; $i<=$#ARGV; $i++) {
  push @addresses, $ARGV[$i];
}

tie my %db, 'GDBM_File', "$dbfile", O_RDWR|O_CREAT, 0666 or die;
$db{$ml} = "0" . $delim . join($delim, @addresses);
untie %db;

open(*F, "$aliases");
my $aliases_org;
while(<F>){
  if ($_ =~ /^$ml\:/) {
  } else {
    $aliases_org .= $_;
  }
}
close(F);
$aliases_org .= "$ml: $command\n";
open(*F, ">$aliases");
print F $aliases_org;
close(F);

`chmod 666 $dbfile`;
`newaliases`;

exit 0;
